function initEnv() {
    $("body").append(DWZ.frag["dwzFrag"]);

    if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch (e) {
        }
    }
    //清理浏览器内存,只对IE起效
    if ($.browser.msie) {
        window.setInterval("CollectGarbage();", 10000);
    }

    $(window).resize(function() {
        initLayout();
        $(this).trigger(DWZ.eventType.resizeGrid);
    });

    var ajaxbg = $("#background,#progressBar");
    ajaxbg.hide();
    $(document).ajaxStart(function() {
        ajaxbg.show();
    }).ajaxStop(function() {
        ajaxbg.hide();
    });

    $("#leftside").jBar({minW: 150, maxW: 700});

    if ($.taskBar)
        $.taskBar.init();
    navTab.init();
    if ($.fn.switchEnv)
        $("#switchEnvBox").switchEnv();
    if ($.fn.navMenu)
        $("#navMenu").navMenu();

    setTimeout(function() {
        initLayout();
        initUI();

        // navTab styles
        var jTabsPH = $("div.tabsPageHeader");
        jTabsPH.find(".tabsLeft").hoverClass("tabsLeftHover");
        jTabsPH.find(".tabsRight").hoverClass("tabsRightHover");
        jTabsPH.find(".tabsMore").hoverClass("tabsMoreHover");

    }, 10);

}
function initLayout() {
    var iContentW = $(window).width() - (DWZ.ui.sbar ? $("#sidebar").width() + 10 : 34) - 5;
    var iContentH = $(window).height() - $("#header").height() - 34;

    $("#container").width(iContentW);
    $("#container .tabsPageContent").height(iContentH - 34).find("[layoutH]").layoutH();
    $("#sidebar, #sidebar_s .collapse, #splitBar, #splitBarProxy").height(iContentH - 5);
    $("#taskbar").css({top: iContentH + $("#header").height() + 5, width: $(window).width()});
}

function initUI(_box) {

    var $p = $(_box || document);

    $("div.panel", $p).jPanel();

    //tables
    $("table.table", $p).jTable();

    // css tables
    $('table.list', $p).cssTable();

    //auto bind tabs
    $("div.tabs", $p).each(function() {
        var $this = $(this);
        var options = {};
        options.currentIndex = $this.attr("currentIndex") || 0;
        options.eventType = $this.attr("eventType") || "click";
        $this.tabs(options);
    });

    $("ul.tree", $p).jTree();
    $('div.accordion', $p).each(function() {
        var $this = $(this);
        $this.accordion({fillSpace: $this.attr("fillSpace"), alwaysOpen: true, active: 0});
    });

    $(":button.checkboxCtrl, :checkbox.checkboxCtrl", $p).checkboxCtrl($p);

    if ($.fn.combox)
        $("select.combox", $p).combox();


    $("textarea.editor", $p).each(function() {
        var editors = $p.data("keditor");
        if (!$.isArray(editors))
            editors = [];
        var $this = $(this);
        var op = {};
        op.resizeType = 1;
        op.pasteType = 1;
        op.width = $this.attr("width") || "";
        op.height = $this.attr("height") || "";
        op.uploadJson = $this.attr("uploadJson");
        op.fileManagerJson = $this.attr("fileManagerJson");
        op.allowFileManager = $this.attr("allowFileManager");
        op.remoteImageLocal = eval($this.attr("remoteImageLocal") || "false");
        op.remoteImageLocalUrl = $this.attr("remoteImageLocalUrl") || "";
        if ($this.attr('wordCount')) {
            op.afterChange = function() {
                $($this.attr('wordCount')).text(this.count('text'));
            };
        }
        if ($this.attr('tools') === "simple") {
            op.items = [
                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                'insertunorderedlist', '|', 'emoticons', 'image', 'link'];
        } else if ($this.attr('tools') === "mini") {
            op.items = [
                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                'removeformat'];
        }
        op.afterBlur = function() {
            this.sync();
        };

        var editor = KindEditor.create(this, op);

        editors.push(editor);
        $p.data("keditor", editors);
    });

    $(".single_image_up", $p).each(function() {
        var editors = $p.data("keditor");
        if (!$.isArray(editors))
            editors = [];
        var $this = $(this);
        var editor = KindEditor.editor({
            uploadJson: $this.attr("uploadJson"),
            afterSelectFile: eval($this.attr("afterSelectFile")),
            afterUpload: eval($this.attr("afterUpload")),
            remoteImageLocal: eval($this.attr("remoteImageLocal") || "false"),
            remoteImageLocalUrl: $this.attr("remoteImageLocalUrl") || ""
        });
        $(this).click(function() {
            editor.loadPlugin('uploadimage', function() {
                editor.plugin.imageDialog({
                    fileUrl: $($this.attr('urlInput')).val(),
                    clickFn: function(url, title) {
                        $($this.attr('urlInput')).val(url);
                        if ($this.attr('callback')) {
                            eval($this.attr('callback')).call(this, url, title);
                        }
                        editor.hideDialog();
                    }
                });
            });
        });
        editors.push(editor);
        $p.data("keditor", editors);
    });

    $(".multi_image_up", $p).each(function() {
        var editors = $p.data("keditor");
        if (!$.isArray(editors))
            editors = [];
        var $this = $(this);
        var editor = KindEditor.editor({
            uploadJson: $this.attr("uploadJson"),
            extraFileUploadParams: DWZ.jsonEval($this.attr("extraFileUploadParams")) || ""
        });
        $(this).click(function() {
            editor.loadPlugin('multiimage', function() {
                editor.plugin.multiImageDialog({
                    clickFn: function(urlList) {
                        if ($this.attr('callback')) {
                            eval($this.attr('callback')).call(this, urlList);
                        }
                        editor.hideDialog();
                    }
                });
            });
        });
        editors.push(editor);
        $p.data("keditor", editors);
    });

    if ($.fn.uploadify) {
        $(":file[uploaderOption]", $p).each(function() {
            var $this = $(this);
            var options = {
                fileObjName: $this.attr("name") || "file",
                auto: true,
                multi: true,
                onUploadError: uploadifyError
            };

            var uploaderOption = DWZ.jsonEval($this.attr("uploaderOption"));
            $.extend(options, uploaderOption);

            DWZ.debug("uploaderOption: " + DWZ.obj2str(uploaderOption));

            $this.uploadify(options);
        });
    }

    // init styles
    $("input[type=text], input[type=password], textarea", $p).addClass("textInput").focusClass("focus");

    $("input[readonly], textarea[readonly]", $p).addClass("readonly");
    $("input[disabled=true], textarea[disabled=true]", $p).addClass("disabled");

    $("input[type=text]", $p).not("div.tabs input[type=text]", $p).filter("[alt]").inputAlert();

    //Grid ToolBar
    $("div.panelBar li, div.panelBar", $p).hoverClass("hover");

    //Button
    $("div.button", $p).hoverClass("buttonHover");
    $("div.buttonActive", $p).hoverClass("buttonActiveHover");

    //tabsPageHeader
    $("div.tabsHeader li, div.tabsPageHeader li, div.accordionHeader, div.accordion", $p).hoverClass("hover");

    //validate form
    $("form.required-validate", $p).each(function() {
        var $form = $(this);
        $form.validate({
            onsubmit: false,
            focusInvalid: false,
            focusCleanup: true,
            errorElement: "span",
            ignore: ".ignore",
            invalidHandler: function(form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = DWZ.msg("validateFormError", [errors]);
                    alertMsg.error(message);
                }
            }
        });

        $form.find('input[customvalid]').each(function() {
            var $input = $(this);
            $input.rules("add", {
                customvalid: $input.attr("customvalid")
            })
        });
    });

    if ($.fn.datepicker) {
        $('input.date', $p).each(function() {
            var $this = $(this);
            $this.attr("autocomplete", "off");
            var opts = {};
            if ($this.attr("dateFmt"))
                opts.pattern = $this.attr("dateFmt");
            if ($this.attr("minDate"))
                opts.minDate = $this.attr("minDate");
            if ($this.attr("maxDate"))
                opts.maxDate = $this.attr("maxDate");
            if ($this.attr("mmStep"))
                opts.mmStep = $this.attr("mmStep");
            if ($this.attr("ssStep"))
                opts.ssStep = $this.attr("ssStep");
            $this.datepicker(opts);
        });
    }

    // navTab
    $("a[target=navTab]", $p).each(function() {
        $(this).click(function(event) {
            var $this = $(this);
            var title = $this.attr("title") || $this.text();
            var tabid = $this.attr("rel") || "_blank";
            var fresh = eval($this.attr("fresh") || "true");
            var external = eval($this.attr("external") || "false");
            var url = decodeURI($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
            DWZ.debug(url);
            if (!url.isFinishedTm()) {
                alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
                return false;
            }
            navTab.openTab(tabid, url, {title: title, fresh: fresh, external: external});

            event.preventDefault();
        });
    });

    //dialogs
    $("a[target=dialog]", $p).each(function() {
        $(this).click(function(event) {
            var $this = $(this);
            var title = $this.attr("title") || $this.text();
            var rel = $this.attr("rel") || "_blank";
            var options = {};
            var w = $this.attr("width");
            var h = $this.attr("height");
            if (w)
                options.width = w;
            if (h)
                options.height = h;
            options.max = eval($this.attr("max") || "false");
            options.mask = eval($this.attr("mask") || "false");
            options.maxable = eval($this.attr("maxable") || "true");
            options.minable = eval($this.attr("minable") || "true");
            options.fresh = eval($this.attr("fresh") || "true");
            options.resizable = eval($this.attr("resizable") || "true");
            options.drawable = eval($this.attr("drawable") || "true");
            options.close = eval($this.attr("close") || "");
            options.param = $this.attr("param") || "";

            var url = decodeURI($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
            DWZ.debug(url);
            if (!url.isFinishedTm()) {
                alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
                return false;
            }
            $.pdialog.open(url, rel, title, options);

            return false;
        });
    });
    $("a[target=ajax]", $p).each(function() {
        $(this).click(function(event) {
            var $this = $(this);
            var rel = $this.attr("rel");
            if (rel) {
                var $rel = $("#" + rel);
                $rel.loadUrl($this.attr("href"), {}, function() {
                    $rel.find("[layoutH]").layoutH();
                });
            }

            event.preventDefault();
        });
    });

    $("div.pagination", $p).each(function() {
        var $this = $(this);
        $this.pagination({
            targetType: $this.attr("targetType"),
            rel: $this.attr("rel"),
            totalCount: $this.attr("totalCount"),
            numPerPage: $this.attr("numPerPage"),
            pageNumShown: $this.attr("pageNumShown"),
            currentPage: $this.attr("currentPage")
        });
    });

    if ($.fn.sortDrag)
        $(".sortDrag", $p).sortDrag();

    // dwz.ajax.js
    if ($.fn.ajaxTodo)
        $("a[target=ajaxTodo]", $p).ajaxTodo();
    if ($.fn.dwzExport)
        $("a[target=dwzExport]", $p).dwzExport();

    if ($.fn.lookup)
        $("a[lookupGroup]", $p).lookup();
    if ($.fn.multLookup)
        $("[multLookup]:button", $p).multLookup();
    if ($.fn.suggest)
        $("input[suggestFields]", $p).suggest();
    if ($.fn.itemDetail)
        $("table.itemDetail", $p).itemDetail();
    if ($.fn.selectedTodo)
        $("a[target=selectedTodo]", $p).selectedTodo();
    if ($.fn.pagerForm)
        $("form[rel=pagerForm]", $p).pagerForm({parentBox: $p});

    // 这里放其他第三方jQuery插件...
    if ($.fn.calculator) {
        $('input.calc', $p).each(function() {
            var $this = $(this);
            var opts = {};
            $this.attr("autocomplete", "off");
            $this.calculator(opts);
        });
    }

    //自动完成
    $("input.autocomplete", $p).each(function() {
        var $this = $(this);
        $this.autocomplete($this.attr("dataurl"), {
            minChars: 1,
            width: $this.width(),
            autoFill: false,
            max: 10,
            formatItem: function(data, i, n, value) {
                return data[1];
            },
            formatResult: function(data, value) {
                return data[1];
            }
        });
        if ($this.attr('callback')) {
            $(this).result(function(event, data, formatted) {
                if (data)
                    eval($this.attr('callback'));
            });
        }

    });

}



